package smoothcraft.Util.tpa;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class Main implements CommandExecutor {
	private static API api = new API();
	@SuppressWarnings("deprecation")
	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) {
		if(cmd.getName().equals("tpa")) {
			if(arg.length < 1) {
				sender.sendMessage(api.getMessage("tpa.error2"));
				return false;
			}
			
			if(Bukkit.getOfflinePlayer(arg[0]).isOnline() == false) {
				sender.sendMessage(api.getMessage("tpa.error1"));
				return false;
			}
			if(api.containsPlayer(sender.getName())) {
				sender.sendMessage(api.getMessage("tpa.error3"));
				return false;
			}
			Player p = Bukkit.getPlayer(arg[0]);
			p.sendMessage(api.getMessage("tpa.tpa2").replaceAll("<tpaAroms>", sender.getName()).replaceAll(",","\n"));
			api.mapJoin(sender.getName(), arg[0]);
			sender.sendMessage(api.getMessage("tpa.tpa1").replaceAll("<tpaAroms>", arg[0]));
			sender.sendMessage(api.getMessage("tpa.timeOut"));
			timeOut(sender.getName());
			return true;
		}
		if(cmd.getName().equals("true")) {
			if(api.containsAroms(sender.getName()) == false) {
				sender.sendMessage(api.getMessage("tpa.error4"));
				return false;
			}
			Player p = Bukkit.getPlayerExact(api.getAroms(sender.getName()));
			api.removeMap(p.getName());
			sender.sendMessage(api.getMessage("tpa.true2"));
			p.sendMessage(api.getMessage("tpa.true1").replaceAll("<accept>", sender.getName()));
			telePlayer(p, (Player)sender);
		}
		if(cmd.getName().equals("false")) {
			String name = api.getAroms(sender.getName());
			if(api.containsAroms(sender.getName()) == false) {
				sender.sendMessage(api.getMessage("tpa.error4"));
				return false;
			}
			if(Bukkit.getOfflinePlayer(name).isOnline() == false) {
				api.removeMap(name);
				sender.sendMessage(api.getMessage("tpa.false").replaceAll("<accept>", sender.getName()));
				return true;
			}
			Player p = Bukkit.getPlayerExact(name);
			api.removeMap(name);
			sender.sendMessage(api.getMessage("tpa.false2"));
			p.sendMessage(api.getMessage("tpa.false1").replaceAll("<accept>", sender.getName()));
		}
		return false;
	}
	private void telePlayer(Player aroms,Player sender) {
		Bukkit.getScheduler().runTaskLaterAsynchronously(smoothcraft.Main.main, new Runnable() {
			public void run() {
				sender.teleport(aroms.getLocation());
			}
		}, 60);
	}
	public void timeOut(String key) {
		Bukkit.getScheduler().runTaskLaterAsynchronously(smoothcraft.Main.main, new Runnable() {
			public void run() {
				api.removeMap(key);
			}
		}, 600);
	}
}
